package xc.com.elasticsearch.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xc.com.course.domain.CoursePub;
import xc.com.elasticsearch.mapper.CourseSearchParam;
import xc.com.elasticsearch.mapper.QueryResponseResult;
import xc.com.elasticsearch.service.ESCourseService;
import xc.com.model.response.CommonCode;
import xc.com.model.response.QueryResult;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class EsCourseServiceImpl implements ESCourseService {
    //    private static final Logger LOGGER = LoggerFactory.getLogger(EsCourseService.class);
//    @Value("${xuecheng.course.index}")
//    private String index;
//    @Value("${xuecheng.course.type}")
//    private String type;
//    @Value("${xuecheng.course.source_field}")
//    private String source_field;
//    @Autowired
//  private RestHighLevelClient restHighLevelClient;
    private static final String index="xc_course";

    private static final String type="doc";

    private static final  String[] list=new String[]{ "id","name","grade","mt","st","charge","valid","pic","qq","price","price_old","status","studymodel","teachmode","expires","pub_ time","start_time","end_time"};
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Override
    public QueryResponseResult<CoursePub> findByList(Integer page, Integer size, CourseSearchParam courseSearchParam) {
        //判断是否为空
        if (courseSearchParam==null){
            //是空就重新new
            courseSearchParam=new CourseSearchParam();
        }
        //创建搜索请求对象
        SearchRequest searchRequest=new SearchRequest(index);
        //设置请求类型
//        searchRequest.searchType(type);
        SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
        //过虑源字段
        searchSourceBuilder.fetchSource(list,new String[]{});
        //创建布尔查询对象
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //条件搜索
        //判断关键字是否为空,根据关键字搜索
        if (StringUtils.isNoneEmpty(courseSearchParam.getKeyword())){
            MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(courseSearchParam.getKeyword(), "name", "description", "teachplan")
                    .minimumShouldMatch("%70")
                    .field("name", 10);
            boolQueryBuilder.must(multiMatchQueryBuilder);
        }
        //判断一级分类是否为空,根据一级分类搜索
        if (StringUtils.isNoneEmpty(courseSearchParam.getMt())){
            boolQueryBuilder.filter(QueryBuilders.termQuery("mt",courseSearchParam.getMt()));
        }
        //判断二级分类是否为空,根据二级分类搜索
        if (StringUtils.isNoneEmpty(courseSearchParam.getSt())){
            boolQueryBuilder.filter(QueryBuilders.termQuery("st",courseSearchParam.getSt()));
        }
        //判断难度等级是否为空,根据难度等级搜索
        if (StringUtils.isNoneEmpty(courseSearchParam.getGrade())){
            boolQueryBuilder.filter(QueryBuilders.termQuery("grade",courseSearchParam.getGrade()));
        }
        //判断页是否小于或等于0
        if (page<=0){
              page=1;
        }
        //判断条是否小于或等于0
        if (size<=0){
            size=20;
        }
        //获取分页页
        Integer Size=(page-1)*size;
        //将分页页传进去
        searchSourceBuilder.from(size);
        //将分页条传进去
        searchSourceBuilder.size(size);
        //高亮设置
        HighlightBuilder highlightBuilder=new HighlightBuilder();
        highlightBuilder.preTags("<font class='eslight'>");
        highlightBuilder.postTags("</font>");
        //设置高亮字段
        highlightBuilder.fields().add(new HighlightBuilder.Field("name"));
        searchSourceBuilder.highlighter(highlightBuilder);
        //布尔查询
        searchSourceBuilder.query(boolQueryBuilder);
        //请求搜索
        searchRequest.source(searchSourceBuilder);
        QueryResult<CoursePub> queryResult=new QueryResult<>();
        List<CoursePub> coursePubList=new ArrayList<>();
        try {
            //执行搜索
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            //获取响应结果
            SearchHits searchHits = searchResponse.getHits();
            //匹配的总记录数
            TotalHits totalHits = searchHits.getTotalHits();
            //匹配的总记录数
            queryResult.setTotal(totalHits.value);
            SearchHit[] hitsHits = searchHits.getHits();
            for (SearchHit hitsHit : hitsHits) {
                CoursePub coursePub=new CoursePub();
                //源文档
                Map<String, Object> sourceAsMap = hitsHit.getSourceAsMap();
                //取出name
                String name =(String) sourceAsMap.get("name");
                coursePub.setName(name);
                //取出id
                String id =(String) sourceAsMap.get("id");
                coursePub.setId(id);
                //取出图片
                String pic = (String) sourceAsMap.get("pic");
                coursePub.setPic(pic);
                //取出qq
                String qq=(String)  sourceAsMap.get("qq");
                coursePub.setQq(qq);
                //取出价格
                Double price=null;
                //取出旧价格
                Double price_old = null;
                try {
                    if (sourceAsMap.get("price")!=null){
                        price = ((Double) sourceAsMap.get("price"));
                    }
                    if(sourceAsMap.get("price_old")!=null ){
                        price_old =((Double) sourceAsMap.get("price_old"));
                    }
                }catch (Exception e) {
                    e.printStackTrace();
               }
                coursePub.setPrice(price);
                coursePub.setPriceOld(price_old);
                //将coursePub对象存放到集合中
                coursePubList.add(coursePub);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //将coursePub集合存放到queryResult对象中
        queryResult.setList(coursePubList);
        QueryResponseResult<CoursePub> queryResponseResult=new QueryResponseResult<>(CommonCode.SUCCESS,queryResult);
        return queryResponseResult;
    }




}
